package com.google.code.jholidays.parsers;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.code.jholidays.events.FixedEvent;
import com.google.code.jholidays.events.FixedEventFactory;
import com.google.code.jholidays.events.parameters.DayMonthPair;

/**
 * Represents parser which can extract {@link DayMonthPair} from {@link String}
 * expression. This parser is used by {@link FixedEventFactory} in the process
 * of construction of {@link FixedEvent} instances
 * 
 * @author tillias
 * @see FixedEventFactory
 * @see FixedEvent
 * @see DayMonthPair
 * 
 */
public class FixedParser {

    /**
     * Parses given string and returns {@link DayMonthPair}
     * 
     * @param expression
     *            String which possible contains pair
     * @return {@link DayMonthPair} if succeded, null otherwise
     */
    public DayMonthPair parseDate(String expression) {
	DayMonthPair result = null;

	try {
	    Matcher matcher = pattern.matcher(expression);

	    if (matcher.matches()) {
		if (matcher.groupCount() == groupsCount) {
		    int dayOfMonth = Integer.valueOf(matcher.group(1));
		    int monthIndex = Integer.valueOf(matcher.group(2));

		    result = new DayMonthPair(dayOfMonth, monthIndex);
		}
	    }
	} catch (Exception e) {
	    // nothing todo heres
	}

	return result;
    }

    /**
     * Checks whether given string represents {@link DayMonthPair}
     * 
     * @param expression
     *            String representation of pair
     * @return True if input string represents {@link DayMonthPair}, false
     *         otherwise
     */
    public boolean matches(String expression) {
	return pattern.matcher(expression).matches();
    }

    private final static Pattern pattern = Pattern
	    .compile("(\\d{1,2})\\.(\\d{1,2})");
    private final static int groupsCount = 2;

}
